//
//  NWPictureBrowserVC.swift
//  Weibo01
//
//  Created by 牛威 on 15/12/16.
//  Copyright © 2015年 牛威. All rights reserved.
//

import UIKit
import SVProgressHUD

private let margin : CGFloat = UIScreen.mainScreen().scale * 4
private let NWPictureBrowserVCCellID = "NWPictureBrowserVCCellID"

class NWPictureBrowserVC: UIViewController {
    
    //MARK: - 实现监听方法
    
    @objc private func close(){
    
      dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    @objc private func save(){
    
    
        //1取出图片
        
        let cell = collection.visibleCells()[0] as! NWPictureBrowserCell
        
        //这里由于网络原因可能加载不到图片,所以是可选的
        
         guard let image = cell.imageView.image else {
        
        return
        
        }
        
        //2保存图片
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
        //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; void * == id == anyObject
        
    }
    
    //MARK: - 改写swift写入照片函数
    
  @objc private  func image(image : UIImage,didFinishSavingWithError error : NSError?,contextInfo : AnyObject?){
    
        let message = (error == nil ) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(message)
    
    
    }
    
    //MARK: - 定义两个属性来接受参数 属性都可以是必选 使用的时候就不用解包了
    
    private var indexPath : NSIndexPath
    private var urls : [NSURL]
    
    //MARK: - 构造函数并实例化属性
    
    /// 重写控制器的构造函数
    ///
    /// - parameter indexPath: 图片的索引
    /// - parameter urls:      图片的url数组
    
    init(indexPath : NSIndexPath,urls : [NSURL]){
    
     
        self.indexPath = indexPath
        self.urls = urls
        
        //这个是UIViewController 的制定构造函数 不要偷懒
        
        super.init(nibName: nil, bundle: nil)
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        
        //设置根视图(如果不指定rect,collection不能显示,因为刚加载视图的时候跟视图view的frame是0)
        
        
        var rect = UIScreen.mainScreen().bounds
        
        //TODO: - 解决两张相邻照片之间的间距问题

         rect.size.width += 20
        
         view = UIView(frame: rect)
        
        setupUI()

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        print(urls)
//        print(indexPath)
        
        //滚动到指定的位置(解决点击都是同一张图片的问题)
    
     collection.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: true)
        

    }
    
   //MARK: - 懒加载控件
    
    /// collectionView
    
    private lazy var collection : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: NWPictureLayout())
    /// 关闭按钮
    private lazy var closeBtn : UIButton = UIButton(title: "关闭", imageName: nil, color: UIColor.whiteColor(), fontSize: 14, backColor: UIColor.darkGrayColor())
    /// 保存按钮
    private lazy var saveBtn : UIButton = UIButton(title: "保存", imageName: nil, color: UIColor.whiteColor(), fontSize: 14, backColor: UIColor.darkGrayColor())
    
    //MARK: - 自定义流水布局
    
    private class NWPictureLayout:UICollectionViewFlowLayout{
    
      
        private override func prepareLayout() {
            super.prepareLayout()
            
            
            //TODO: - UIScreen.mainScreen() 这里就是照片间距递增的原因
            
            itemSize = collectionView!.bounds.size
            
            minimumInteritemSpacing = 0
            
            minimumLineSpacing = 0
            
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            
            collectionView?.showsHorizontalScrollIndicator = false
            
            collectionView?.bounces = false
            
        }
    
    }

}

//MARK: - 设置界面

extension NWPictureBrowserVC {



    private func setupUI(){
    
        //1 添加控件
        
        view.addSubview(collection)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        //2设置约束
        

        
        collection.frame = view.bounds
        
        closeBtn.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(view.snp_left).offset(margin)
            make.bottom.equalTo(view.snp_bottom).offset(-margin)
            make.height.equalTo(36)
            make.width.equalTo(100)
        }
        
        saveBtn.snp_makeConstraints { (make) -> Void in
            
            make.right.equalTo(view.snp_right).offset(-28) //解决转场动画后 按钮偏移20点的问题
            make.bottom.equalTo(view.snp_bottom).offset(-margin)
            make.height.equalTo(36)
            make.width.equalTo(100)

        }
        
        //3添加监听方法
        
        closeBtn.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveBtn.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        

       //4准备collection的界面
        
        
       prepareCollection()
    }
    
    

    //MARK: -collection的设置
    
    private func prepareCollection(){
    
         //注册cell
        
        collection.registerClass(NWPictureBrowserCell.self, forCellWithReuseIdentifier: NWPictureBrowserVCCellID)
        
        //设置数据源方法
        
        collection.dataSource = self
        
    }

}


extension NWPictureBrowserVC : UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collection.dequeueReusableCellWithReuseIdentifier(NWPictureBrowserVCCellID, forIndexPath: indexPath) as! NWPictureBrowserCell
        
//        cell.backgroundColor = UIColor.randomColor()
        
        cell.imageUrl = urls[indexPath.item]
        
        cell.pictureDelegate = self
        
        return cell
    }

}


//MARK: - 实现照片浏览的代理方法

extension NWPictureBrowserVC : NWPictureBrowserCellDelegate {

    func pictureBrowserCellDelegate() {
        
        self.close()
    }


}

//MARK: - 实现解除自定义转场动画的方法

extension NWPictureBrowserVC : NWPictureAnimatorDismissDelegate {


    func imageViewForDismiss() -> UIImageView {
        
        let iv = UIImageView()
        
        //1设置填充模式
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        //2取得图片
        
        let cell = collection.visibleCells()[0] as! NWPictureBrowserCell
        
        iv.image = cell.imageView.image

        
        //3转换位置
        
        iv.frame = cell.scroll.convertRect(cell.imageView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        
        return iv
    }

    func indexPathForDismiss() -> NSIndexPath {
        
        return collection.indexPathsForVisibleItems()[0]
    }


}